import json
from channels.generic.websocket import AsyncWebsocketConsumer


class DailyAttendanceConsumer(AsyncWebsocketConsumer):
    """ 微信小程序打开二维码时的websocket，用于通知刷二维码是否成功 """

    # 建立连接的回调
    async def connect(self):
        self.username = self.scope['url_route']['kwargs']['username']

        await self.channel_layer.group_add(
            self.username,
            self.channel_name
        )

        await self.accept()

    # 断开连接的回调
    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(
            self.username,
            self.channel_name
        )

    # 收到消息的回调
    async def receive(self, text_data=None):
        # 发送消息给前端
        await self.send(text_data=json.dumps(text_data))

        # await self.channel_layer.group_send(
        #     self.group_name,
        #     {
        #         'type': 'chat_message',
        #         'message': 'hello world'
        #     }
        # )

    # # 发送消息指定的处理方法
    # async def chat_message(self, event):
    #     print(event)
    #     message = event['message']
    #
    #     # Send message to WebSocket
    #     await self.send(text_data=json.dumps({
    #         'message': message
    #     }))
